<template>
  <div class='tabbar'>
    <el-tabs v-model="actionsKay" type="card" editable class="demo-tabs" @tab-click="onHandle" :plain="true"
      @tab-remove="removeTab">
      <el-tab-pane v-for="item in tabsList" :key="item.path" :label="$t(item.title)" :name="item.path">
        {{ item.content }}
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script setup lang='ts'>
import { computed, onMounted, ref, watch } from 'vue'
// 消息提醒
import { ElMessage } from 'element-plus'
// vuex
import { useStore } from '@/store/index';
// 路由
import { useRoute, useRouter } from 'vue-router'
// 数组内容的类型
import { Itab } from '@/store/type'
const store = useStore()
const route = useRoute()
const router = useRouter()
// 属性
const tabsList = computed(() => {
  return store.getters['tabState/getAddTab']
})
// 索引
const actionsKay = ref('')
// 添加tab
const addTab = () => {
  // 通过结构赋值 拿到数据
  const { meta, path } = route
  // 整合数据
  const tab: Itab = {
    path: path,
    title: meta.title as string
  }
  // 添加
  store.commit('tabState/addTab', tab)
}
// 通过 路由地址的变化 去添加tab
watch(() => route.path, () => {
  actionsKay.value = route.path
  addTab()
})
// 点击 tab 切换
const onHandle = (e: any) => {
  router.push({ path: e.props.name })
}

// 删除 tab 
const removeTab = (targetName: string) => {
  // console.log(targetName); 路径
  // 判断 留一个
  if (tabsList.value.length === 1) {
    return ElMessage.error('最后一页了哦')
  }
  // 如果删除的是当前页面
  if (targetName === actionsKay.value) {
    tabsList.value.forEach((tab: Itab, index: number) => {
      // 判断 当前点击是当前页面
      if (tab.path == targetName) {
        // 重新设置索引
        const newxActiveKay = tabsList.value[index + 1] || tabsList.value[index - 1]
        if (newxActiveKay) {
          actionsKay.value = newxActiveKay.path
        }
      }
    });
  }
  // 移除 tab
  store.commit('tabState/closeTabs', targetName)
}
// 刷新缓存数据
const refresh = () => {
  window.addEventListener('beforeunload', (e) => {
    // 存入缓存中
    sessionStorage.setItem('TABS_router', JSON.stringify(tabsList.value))
  })
  // 取缓存
  let session = sessionStorage.getItem("TABS_router")
  // 并且依次添加到 tab栏中
  if (session) {
    let tabItem = JSON.parse(session)
    tabItem.forEach((tab: string) => {
      store.commit("tabState/addTab", tab)
    })
  }
}
onMounted(() => {
  addTab()
  refresh()
})
</script>
<style lang='less' scoped></style>